/**
 * 多窗口信息发送服务
 * 
 */
interface PostMessageBase {
    source: 'ceair-auto-content-script'
}
interface FirstPostMessage extends PostMessageBase {
    hello: boolean
}
interface ConnectPostMessage extends PostMessageBase {
    connect: boolean
    data?: any
}
const taskStack: any[] = [];
let connectMessageTimeoutId: number;
let OPEN_MESSAGE = false;
let POST_ORIGIN: any;
let RETRY_CONNECT_TIME = 0;
let CALLBACK:Function;
export function setMessageListener(messageCallback?: (data: any) => void) {
    window.addEventListener("message", function (e) {
        if (e.origin.includes("http://www.ceair.com") && e.data.source === "ceair-auto-fixed") {
            if (e.data.reply) {
                console.log('content-script收到了 fixed');
                this.clearTimeout(connectMessageTimeoutId);
                POST_ORIGIN = e.origin;
                startSendMessage(); // 有数据则发送数据
            }
            RETRY_CONNECT_TIME = 0;
            messageCallback && messageCallback(e.data);
        }
    }, false);
    connectFixedMessage();
    OPEN_MESSAGE = true;
}
function validConnect(): boolean {
    return !!POST_ORIGIN && OPEN_MESSAGE;
}
function startSendMessage() {
    if (validConnect()) {
        taskStack.forEach(data => {
            const connectPostMessage: ConnectPostMessage = { source: 'ceair-auto-content-script', connect: true, data };
            window.postMessage(connectPostMessage, POST_ORIGIN)
        });
        taskStack.length = 0;
    }
}
export function sendMessage(data: any, messageCallback?: (data: any) => any) {
    !OPEN_MESSAGE && setMessageListener(messageCallback);
    taskStack.push(data);
    taskStack.length > 0 && startSendMessage();
}

function connectFixedMessage() {
    console.log('connect fixed………………');
    window.postMessage({
        source: 'ceair-auto-content-script',
        hello: true,
    }, 'http://www.ceair.com/*');
    connectMessageTimeoutId = window.setTimeout(() => {
        connectFixedMessage();
        RETRY_CONNECT_TIME += 1;
        taskStack.length > 0 && startSendMessage();
    }, 8000);
}